package test.clockwisematrix;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        int[][] matrix = {{1, 11},
                {2, 12},
                {3, 13},
                {4, 14},
                {5, 15},
                {6, 16},
                {7, 17},
                {8, 18},
                {9, 19},
                {10, 20}};

        System.out.println(Arrays.toString(new Solution().spiralOrder(matrix)));
    }

    public int[] spiralOrder(int[][] matrix) {

//        matrix =
//        [[1,2,3,4],
//        [5,6,7,8],
//        [9,10,11,12],
//        [9,10,11,12]]
//        输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 /*

[[1,11],
[2,12],
[3,13],
[4,14],
[5,15],
[6,16],
[7,17],
[8,18],
[9,19],
[10,20]]
输出
[1,11,12,13,14,15,16,17,18,19,20,10,9,8,7,6,5,4,3,2,3,4,5,6,7,8,9]
预期结果
[1,11,12,13,14,15,16,17,18,19,20,10,9,8,7,6,5,4,3,2]


                */

        if (matrix.length == 0) {
            return new int[0];
        }
        List<Integer> result = new ArrayList<>();

        int maxX = matrix[0].length;
        int maxY = matrix.length;
        int offset = 0;

        long num = Math.round(Math.min(maxX, maxY) / 2.0);
        for (int j = 0; j < num; j++) {
            for (int i = offset; i < maxX; i++) {
                result.add(matrix[offset][i]);
            }
            for (int i = offset + 1; i < maxY && maxX > 0; i++) {
                result.add(matrix[i][maxX - 1]);
            }
            for (int i = maxX - 2; i >= offset && offset + 1 < maxY; i--) {
                result.add(matrix[maxY - 1][i]);
            }
            for (int i = maxY - 2; i > offset && maxX - 2 >= offset; i--) {
                result.add(matrix[i][offset]);
            }
            maxX--;
            maxY--;
            offset++;
        }

        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}